<?
require_once(dirname(__FILE__) . '/../../classes/module_interface.inc.php');
require_once(dirname(__FILE__) . '/../../classes/strings.inc.php');
require_once(dirname(__FILE__) . '/config.inc.php');

class LoggerModulePopularity extends LoggerStrings implements LoggerModuleInterface
{
    protected $database;

    public function __construct(LoggerDatabase $database) 
    {
        $this->database = $database;
        $this->stringsTable = 'module_popularity_strings';
    }

    public function PrepareParseSession()
    {
        return true;
    }

    public function ParseHit(&$hit)
    {
        if (isset($hit['modules']['robots']))
            return false;

        $parseUrlResult = $this->ParseUrl($hit['source']['url']);
        if ($parseUrlResult === false)
            return false;

        $serverStr  = $parseUrlResult['server'];
        $pathStr    = $parseUrlResult['path'];
        $queryStr   = $parseUrlResult['query'];

        if (!preg_match('/^text\/.*/', $hit['source']['mimetype']))
        {
            if (LoggerModulePopularityConfig::$onlyText)
                return false;

            if (LoggerModulePopularityConfig::$notTextOnlyFromExternalLinks)
            {
                $parseRefResult = $this->ParseUrl($hit['source']['referer']);
                if ($parseRefResult === false)
                    return false;

                if ($parseRefResult['server'] == $serverStr || in_array($parseRefResult['server'], LoggerConfig::$myServers))
                    return false;
            }
        }

        if (!in_array($serverStr, LoggerConfig::$myServers))
            return false;

        $hit['modules']['popularity']['serverStr']  = $serverStr;
        $hit['modules']['popularity']['pathStr']    = $pathStr;
        $hit['modules']['popularity']['queryStr']   = $queryStr;

        if (preg_match('/^\/*(.*)\/*$/', $pathStr, $match))
            $path = $match[1];

        $dirsStr = explode('/', $path, 4);
        $fileStr = array_pop($dirsStr);
        $fileId = $this->GetStringId($fileStr, $hit['source']['time']);
        $dirsId = array(0, 0, 0);
        for ($i = 0; $i < 3; $i++)
        {
            if (isset($dirsStr[$i]) && $dirsStr[$i])
                $dirsId[$i] = $this->GetStringId($dirsStr[$i], $hit['source']['time']);
        }

        $queryId = $this->GetStringId($queryStr, $hit['source']['time']);
        $titleId = $this->GetStringId($hit['source']['title'], $hit['source']['time']);

        $visitor    = intval($hit['source']['visitor']);
        $session    = intval($hit['source']['session']);
        $time   = '\'' . mysql_escape_string($hit['source']['time']) . '\'';
        $file   = intval($fileId);
        $dir1   = intval($dirsId[0]);
        $dir2   = intval($dirsId[1]);
        $dir3   = intval($dirsId[2]);
        $query  = intval($queryId);
        $title  = intval($titleId);

        $InsertSQL = 'INSERT INTO `[PREF]module_popularity` (`visitor`, `session`, `time`, `dir1`, `dir2`, `dir3`, `file`, `query`, `title`) ';
        $InsertSQL .= 'VALUES('.$visitor.', '.$session.', '.$time.', '.$dir1.', '.$dir2.', '.$dir3.', '.$file.', '.$query.', '.$title.')';
        $result = $this->database->Query($InsertSQL);
        if (!$result)
            trigger_error('Database Error: ' . $this->database->Error(), E_USER_ERROR);

        $logId = $this->database->InsertId();
        $hit['modules']['popularity']['id'] = $logId;

        return true;
    }

    public function Archive()
    {
        $date = LoggerModulePopularityConfig::GetArchiveDate();
        $dateEscaped = '\''.mysql_escape_string($date).'\'';

        $this->database->Query('LOCK TABLES `[PREF]module_popularity` WRITE, `[PREF]module_popularity_archive` WRITE');

        $ArchiveSQL = 'INSERT INTO `[PREF]module_popularity_archive` (`date`, `dir1`, `dir2`, `dir3`, `file`, `query`, `title`, `count`) ';
        $ArchiveSQL .= 'SELECT DATE(`time`), `dir1`, `dir2`, `dir3`, `file`, `query`, `title`, COUNT(*) FROM `[PREF]module_popularity` WHERE `time`<'.$dateEscaped.' ';
        $ArchiveSQL .= 'GROUP BY DATE(`time`), `dir1`, `dir2`, `dir3`, `file`, `query`, `title`';
        $this->database->Query($ArchiveSQL);
        $DeleteSQL = 'DELETE FROM `[PREF]module_popularity` WHERE `time`<'.$dateEscaped;
        $this->database->Query($DeleteSQL);

        $this->database->Query('UNLOCK TABLES');
    }

    public function Purge()
    {
        $date = LoggerModulePopularityConfig::GetPurgeDate();
        $dateEscaped = '\''.mysql_escape_string($date).'\'';

        $DeleteSQL = 'DELETE FROM `[PREF]module_popularity_archive` WHERE `date`<'.$dateEscaped;
        $this->database->Query($DeleteSQL);
        $DeleteSQL = 'DELETE FROM `[PREF]module_popularity` WHERE `time`<'.$dateEscaped;
        $this->database->Query($DeleteSQL);

        $OptimizeSQL = 'OPTIMIZE TABLE `[PREF]module_popularity`';
        $this->database->Query($OptimizeSQL);
        $OptimizeSQL = 'OPTIMIZE TABLE `[PREF]module_popularity_archive`';
        $this->database->Query($OptimizeSQL);

        $this->PurgeStrings($date);
    }
}